package org.dawning.shop.order.command.handler;

import lombok.extern.log4j.Log4j;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.commandhandling.model.Repository;
import org.dawning.shop.common.commands.order.CreateOrderCommand;
import org.dawning.shop.common.domain.order.OrderProduct;
import org.dawning.shop.common.utils.BeanMapper;
import org.dawning.shop.common.utils.GenerateSku;
import org.dawning.shop.order.command.aggregate.OrderAggregate;
import org.dawning.shop.order.infrastructure.rpc.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


/**
 *
 * Created by miou on 2017/6/15 0015.
 */
@Component
@Log4j
public class OrderHandler {


    /*@Autowired
    private ProductService productService;*/

    @Autowired
    private Repository<OrderAggregate> repository;


    /**生成订单命令处理器*/
    @CommandHandler
    public void handle(CreateOrderCommand command) throws Exception {
        log.info("apply create product command : " + command.toString());

        Map<String,OrderProduct> orderProducts = new HashMap<>();

        command.getProducts().forEach((productDto)->{
            OrderProduct orderProduct = BeanMapper.map(productDto,OrderProduct.class);
            String sku = GenerateSku.generateSku(productDto.getProductId(),productDto.getAttributes());
            orderProducts.put(sku,orderProduct);
        });
        repository.newInstance(()->new OrderAggregate(command.getOrderId(),command.getBuyer(),orderProducts,command.getAddress()));
    }

}
